import i18n from '@root/i18n';
import { StorageAPI } from './Extension Module/Storage';
import './Extension Module/enter';
import { car_information } from './Extension Module/car_imformation';
import './Extension Module/buyCar';
import './Extension Module/rank';
import './Extension Module/playerInteract';
import { ChangeType } from './Extension Module/changeType';
import { DHM } from './Extension Module/dhm';

// 由于服务端中用户群体广泛，来源多样，建议在每个 t 函数中显式传入当前用户的语言标识，以确保多语言内容能够正确匹配用户所需的语言版本。
console.clear();
console.log('(server)：', i18n.t('welcome_game', { lng: 'en' }));
console.log('(server)：', i18n.t('welcome_ap', { lng: 'en' }));
world.addCollisionFilter('player', 'player');
const rightOption = {
  '1': 2,
  '2': 1,
  '3': 2,
  '4': 2,
  '5': 1,
  '6': 1,
  '7': 1,
  '8': 1,
  '9': 1,
};
type description =
  | 'description.1'
  | 'description.2'
  | 'description.3'
  | 'description.4'
  | 'description.5'
  | 'description.6'
  | 'description.7'
  | 'description.8'
  | 'description.9';
type welcome =
  | 'welcome.firstEnter_welcome1'
  | 'welcome.firstEnter_welcome2'
  | 'welcome.firstEnter_welcome3'
  | 'welcome.firstEnter_welcome4'
  | 'welcome.firstEnter_welcome5'
  | 'welcome.firstEnter_welcome6'
  | 'welcome.firstEnter_welcome7';
async function askTakeDrivingLicenseExam(entity: GamePlayerEntity) {
  let score = 0;
  const questions = {
    '1': {
      q: i18n.t('question.1', { lng: entity.language }),
      '1': i18n.t('answer.1.1', { lng: entity.language }),
      '2': i18n.t('answer.1.2', { lng: entity.language }),
    },
    '2': {
      q: i18n.t('question.2', { lng: entity.language }),
      '2': i18n.t('answer.2.2', { lng: entity.language }),
      '1': i18n.t('answer.2.1', { lng: entity.language }),
    },
    '3': {
      q: i18n.t('question.3', { lng: entity.language }),
      '1': i18n.t('answer.3.1', { lng: entity.language }),
      '2': i18n.t('answer.3.2', { lng: entity.language }),
    },
    '4': {
      q: i18n.t('question.4', { lng: entity.language }),
      '1': i18n.t('answer.4.1', { lng: entity.language }),
      '2': i18n.t('answer.4.2', { lng: entity.language }),
    },
    '5': {
      q: i18n.t('question.5', { lng: entity.language }),
      '2': i18n.t('answer.5.2', { lng: entity.language }),
      '1': i18n.t('answer.5.1', { lng: entity.language }),
    },
    '6': {
      q: i18n.t('question.6', { lng: entity.language }),
      '1': i18n.t('answer.6.1', { lng: entity.language }),
      '2': i18n.t('answer.6.2', { lng: entity.language }),
    },
    '7': {
      q: i18n.t('question.7', { lng: entity.language }),
      '1': i18n.t('answer.7.1', { lng: entity.language }),
      '2': i18n.t('answer.7.2', { lng: entity.language }),
    },
    '8': {
      q: i18n.t('question.8', { lng: entity.language }),
      '1': i18n.t('answer.8.1', { lng: entity.language }),
      '2': i18n.t('answer.8.2', { lng: entity.language }),
    },
    '9': {
      q: i18n.t('question.9', { lng: entity.language }),
      '1': i18n.t('answer.9.1', { lng: entity.language }),
      '2': i18n.t('answer.9.2', { lng: entity.language }),
    },
  };
  await entity.player.dialog<GameTextDialogParams>({
    type: GameDialogType.TEXT,
    title: i18n.t('exam.title', { lng: entity.language }),
    content: i18n.t('exam.introduction', { lng: entity.language }),
  });
  for (let i = 0; i < 9; i++) {
    const question = questions[`${i + 1}` as keyof typeof questions].q;
    console.log(question);
    const answer = await entity.player.dialog<GameSelectDialogParams>({
      type: GameDialogType.SELECT,
      title: i18n.t('exam.title', { lng: entity.language }),
      content: `${question}

A: ${questions[String(i + 1) as keyof typeof questions]['1']}
B: ${questions[String(i + 1) as keyof typeof questions]['2']}`,
      options: ['A', 'B'],
    });
    if (answer) {
      switch (answer.value) {
        case 'A':
          if (rightOption[String(i + 1) as keyof typeof rightOption] === 1) {
            score += 3;
            await entity.player.dialog<GameTextDialogParams>({
              type: GameDialogType.TEXT,
              title: i18n.t('exam.title', { lng: entity.language }),
              content: i18n.t('exam.correct', { lng: entity.language }),
            });
          } else {
            score -= 1;
            await entity.player.dialog<GameTextDialogParams>({
              type: GameDialogType.TEXT,
              title: i18n.t('exam.title', { lng: entity.language }),
              content: i18n.t('exam.wrong', { lng: entity.language }),
            });
          }
          break;
        case 'B':
          if (rightOption[String(i + 1) as keyof typeof rightOption] === 2) {
            score += 3;
            await entity.player.dialog<GameTextDialogParams>({
              type: GameDialogType.TEXT,
              title: i18n.t('exam.title', { lng: entity.language }),
              content: i18n.t('exam.correct', { lng: entity.language }),
            });
          } else {
            score -= 1;
            await entity.player.dialog<GameTextDialogParams>({
              type: GameDialogType.TEXT,
              title: i18n.t('exam.title', { lng: entity.language }),
              content: i18n.t('exam.wrong', { lng: entity.language }),
            });
          }
          break;
      }
    } else {
      await entity.player.dialog<GameTextDialogParams>({
        type: GameDialogType.TEXT,
        title: i18n.t('exam.title', { lng: entity.language }),
        content: i18n.t('exam.closed', { lng: entity.language }),
      });
      break;
      //用户关闭了对话框
    }
  }
  await entity.player.dialog<GameTextDialogParams>({
    type: GameDialogType.TEXT,
    title: i18n.t('exam.title', { lng: entity.language }),
    content: i18n.t('exam.end', { lng: entity.language, score: score }),
  });
  return score;
}

i18n.init({
  lng: 'en',
  fallbackLng: 'en',
});

remoteChannel.onServerEvent((event) => {
  console.log(event.args.type);
  if (event.args.type === 'setLanguage') {
    const entity = event.entity as GamePlayerEntity;
    const language = event.args.data as 'en' | 'zh-CN';
    entity.language = language;
    console.log(entity.language);
  }
});
setInterval(async () => {
  world.querySelectorAll('player').forEach((entity) => {
    remoteChannel.sendClientEvent(entity, {
      type: 'velocity',
      data: Number(
        entity.velocity.distance(new GameVector3(0, 0, 0)) * 10
      ).toFixed(3),
    });
  });
}, 1000);
world.onPlayerJoin(async ({ entity }) => {
  await StorageAPI.loadPlayer(entity);
  await StorageAPI.savePlayer(entity);
  entity.player.scale = 0.6;
  entity.player.forceRespawn();
  entity.player.walkAcceleration = 0.349609375;
  entity.player.walkSpeed = 0.3994140625;
  if (!entity.haspassed) {
    await entity.player.dialog<GameTextDialogParams>({
      type: GameDialogType.TEXT,
      title: i18n.t('welcome.title'),
      content: i18n.t('welcome.firstEnter_welcome1', {
        name: entity.player.name,
        lng: entity.language,
      }),
    });
    const welcomeKeys: welcome[] = [
      'welcome.firstEnter_welcome2',
      'welcome.firstEnter_welcome3',
      'welcome.firstEnter_welcome4',
      'welcome.firstEnter_welcome5',
      'welcome.firstEnter_welcome6',
      'welcome.firstEnter_welcome7',
    ];
    for (const key of welcomeKeys) {
      await entity.player.dialog<GameTextDialogParams>({
        type: GameDialogType.TEXT,
        title: i18n.t('welcome.title'),
        content: i18n.t(key, { lng: entity.language }),
      });
    }
  }
});
const robot = world.querySelector('#机器人') as GameEntity;
robot.enableInteract = true;
robot.interactHint = '机器人';
robot.interactRadius = 8;
robot.onInteract(async ({ entity }) => {
  let options = [
    i18n.t('robot.view_rules', { lng: entity.language }),
    i18n.t('robot.view_gallery', { lng: entity.language }),
  ];
  if (!entity.haspassed) {
    options = [
      i18n.t('robot.take_driving_license_exam', { lng: entity.language }),
    ];
  }
  const robotDialog1 = await entity.player.dialog<GameSelectDialogParams>({
    type: GameDialogType.SELECT,
    title: i18n.t('robot.name', { lng: entity.language }),
    content: i18n.t('robot.greet', {
      name: entity.player.name,
      lng: entity.language,
    }),
    options,
  });
  if (robotDialog1) {
    switch (robotDialog1.value) {
      case i18n.t('robot.view_gallery', { lng: entity.language }): //查看图鉴
        const d1 = await entity.player.dialog<GameSelectDialogParams>({
          type: GameDialogType.SELECT,
          title: i18n.t('gallery.title', { lng: entity.language }),
          content: i18n.t('gallery.content', { lng: entity.language }),
          options: Object.keys(car_information).map(
            (key) => car_information[key as keyof typeof car_information].name
          ),
        });
        if (d1) {
          const car =
            car_information[
              Object.keys(car_information).find(
                (key) =>
                  car_information[key as keyof typeof car_information].name ===
                  d1.value
              ) as keyof typeof car_information
            ];
          await entity.player.dialog<GameTextDialogParams>({
            type: GameDialogType.TEXT,
            title: i18n.t('description.gallery', { lng: entity.language }),
            content: `
              ${i18n.t('car_information.name', { name: car.name, lng: entity.language })},
              ${i18n.t('car_information.speed', { speed: car.speed, lng: entity.language })},
              ${i18n.t('car_information.jumpPower', { jumpPower: car.jumpPower, lng: entity.language })},
              ${i18n.t('car_information.acceleration', { acceleration: car.acceleration, lng: entity.language })},
              ${i18n.t('car_information.isDz', { isDz: car.isDz, lng: entity.language })},
              ${i18n.t('car_information.fuelType', { fuelType: car.fuelType, lng: entity.language })},
            `,
          });
        }
        break;
      case i18n.t('robot.take_driving_license_exam', { lng: entity.language }):
        const score = await askTakeDrivingLicenseExam(entity);
        if (score >= 18) {
          entity.haspassed = true;
          await entity.player.dialog<GameTextDialogParams>({
            type: GameDialogType.TEXT,
            title: i18n.t('exam.title', { lng: entity.language }),
            content: i18n.t('exam.passed', { lng: entity.language }),
          });
          await StorageAPI.savePlayer(entity);
          entity.cars.push({
            id: 'car_01',
            name: 'FCX Mopeak SC-ONE 银白', //因为玩家可以更改赛车名字，所以名字不使用i18n进行翻译
          });
          entity.player.directMessage(
            i18n.t('newCar.content', {
              car: 'FCX Mopeak SC-ONE 银白',
              lng: entity.language,
            })
          );
        }
        break;
      case i18n.t('robot.view_rules', { lng: entity.language }): //查看图鉴
        for (let i = 1; i < 9; i++) {
          await entity.player.dialog<GameTextDialogParams>({
            type: GameDialogType.TEXT,
            title: i18n.t('description.gallery', { lng: entity.language }),
            content: i18n.t(`description.${i}` as description, {
              lng: entity.language,
            }),
          });
        }
        break;
    }
  }
});
world.onPress(async ({ entity, button, raycast }) => {
  if (button === GameButtonType.ACTION1) {
    if (entity.hasTag('ingame')) {
      return;
    }
    const panel = await entity.player.dialog<GameSelectDialogParams>({
      type: GameDialogType.SELECT,
      title: i18n.t('control_panel.title', { lng: entity.language }),
      content: i18n.t('control_panel.information', {
        lng: entity.language,
        name: entity.player.name,
        id: entity.player.userId,
        level: entity.level,
        exp: entity.exp,
        speed: entity.fastestRecord,
        money: entity.coin,
        carCount: entity.cars.length,
        car: entity.useCar.name,
        hasDrivingLicense: entity.haspassed
          ? i18n.t('common.yes', { lng: entity.language })
          : i18n.t('common.no', { lng: entity.language }),
      }),
      options: [
        i18n.t('common.save', { lng: entity.language }),
        i18n.t('control_panel.my_garage', { lng: entity.language }),
        i18n.t('control_panel.settings', { lng: entity.language }),
        i18n.t('control_panel.witness', { lng: entity.language }),
      ],
    });
    if (!panel) {
      return;
    } //用户关闭了对话框
    switch (panel.value) {
      case i18n.t('control_panel.witness', { lng: entity.language }):
        const witness = await entity.player.dialog<GameSelectDialogParams>({
          type: GameDialogType.SELECT,
          title: i18n.t('control_panel.witness', { lng: entity.language }),
          content: i18n.t('control_panel.witness_select', {
            lng: entity.language,
          }),
          options: world.querySelectorAll('player').map((x) => x.player.name),
        });
        if (!witness) {
          return;
        }
        entity.player.cameraEntity =
          world
            .querySelectorAll('player')
            .find((x) => x.player.name === witness.value) ?? entity;
        break;
      case i18n.t('common.save', { lng: entity.language }):
        await StorageAPI.savePlayer(entity);
        await entity.player.dialog<GameTextDialogParams>({
          type: GameDialogType.TEXT,
          title: i18n.t('control_panel.title', { lng: entity.language }),
          content: i18n.t('common.save_success', { lng: entity.language }),
        });
        break;
      case i18n.t('control_panel.settings', { lng: entity.language }):
        const setting = await entity.player.dialog<GameSelectDialogParams>({
          type: GameDialogType.SELECT,
          title: i18n.t('control_panel.setting_options.title', {
            lng: entity.language,
          }),
          content: i18n.t('control_panel.setting_options.content', {
            lng: entity.language,
          }),
          options: [
            i18n.t('control_panel.setting_options.language_setting', {
              lng: entity.language,
            }),
          ],
        });
        if (!setting) {
          return;
        }
        switch (setting.value) {
          case i18n.t('control_panel.setting_options.language_setting', {
            lng: entity.language,
          }):
            entity.language = entity.language === 'en' ? 'zh-CN' : 'en';
            entity.player.directMessage(
              i18n.t('common.language_switch', { lng: entity.language })
            );
            break;
        }
        break;
      case i18n.t('control_panel.my_garage', { lng: entity.language }):
        if (entity.cars.length === 0) {
          await entity.player.dialog<GameTextDialogParams>({
            type: GameDialogType.TEXT,
            title: i18n.t('garage.title', { lng: entity.language }),
            content: i18n.t('garage.no_cars', { lng: entity.language }),
          });
          return;
        } else {
          const select_car1 =
            await entity.player.dialog<GameSelectDialogParams>({
              type: GameDialogType.SELECT,
              title: i18n.t('garage.title', { lng: entity.language }),
              content: i18n.t('garage.select_car', { lng: entity.language }),
              options: entity.cars.map((car) => car.name),
            });
          if (!select_car1) {
            return;
          } //用户关闭了对话框
          const selectedCar = entity.cars[select_car1.index];
          if (!selectedCar) {
            return;
          }
          let information = ChangeType.getCarInformation(selectedCar.id);
          if (information.isDz) {
            information = {
              id: information.id,
              name: selectedCar.name,
              speed: entity.dz.speed[entity.dz.name.indexOf(selectedCar.name)],
              jumpPower:
                entity.dz.jumpPower[entity.dz.name.indexOf(selectedCar.name)],
              acceleration:
                entity.dz.acceleration[
                  entity.dz.name.indexOf(selectedCar.name)
                ],
              isDz: true,
              fuelType: information.fuelType,
            };
          }
          const select_car2 =
            await entity.player.dialog<GameSelectDialogParams>({
              type: GameDialogType.SELECT,
              title: i18n.t('garage.title', { lng: entity.language }),
              content: `
            ${i18n.t('car_information.name', { name: information.name, lng: entity.language })},
            ${i18n.t('car_information.speed', { speed: information.speed, lng: entity.language })},
            ${i18n.t('car_information.jumpPower', { jumpPower: information.jumpPower, lng: entity.language })},
            ${i18n.t('car_information.acceleration', { acceleration: information.acceleration, lng: entity.language })},
            ${i18n.t('car_information.isDz', { isDz: information.isDz, lng: entity.language })},
            ${i18n.t('car_information.fuelType', { fuelType: information.fuelType, lng: entity.language })},
            `,
              options: [
                i18n.t('garage.select_car', { lng: entity.language }),
                i18n.t('garage.close', { lng: entity.language }),
              ],
            });
          if (!select_car2) {
            return;
          }
          switch (select_car2.value) {
            case i18n.t('garage.select_car', { lng: entity.language }):
              if (information.isDz) {
                entity.useCar = {
                  id: information.id,
                  name: selectedCar.name,
                  speed:
                    entity.dz.speed[entity.dz.name.indexOf(information.name)],
                  jumpPower:
                    entity.dz.jumpPower[
                      entity.dz.name.indexOf(information.name)
                    ],
                  acceleration:
                    entity.dz.acceleration[
                      entity.dz.name.indexOf(information.name)
                    ],
                  isDz: true,
                  fuelType: information.fuelType,
                };
              }
              entity.useCar = information;
              entity.player.directMessage(
                i18n.t('garage.set_car_success', {
                  car: selectedCar.name,
                  lng: entity.language,
                })
              );
              break;
            case i18n.t('garage.close', { lng: entity.language }):
              break;
          }
        }
    }
  }
});

const admins = ['383021551268490', '302455011206115']; //管理员名单
world.onChat(async ({ entity, message }) => {
  if (admins.includes(entity.player?.userId as string)) {
    if (message.startsWith('$')) {
      try {
        await entity.player?.dialog<GameTextDialogParams>({
          type: GameDialogType.TEXT,
          title: 'Admin Command',
          content: eval(message.slice(1)),
        });
      } catch (error) {
        await entity.player?.dialog<GameTextDialogParams>({
          type: GameDialogType.TEXT,
          title: 'Admin Command',
          content: `Error: ${error}`,
        });
      }
    }
  }
});

world.onPlayerLeave(async ({ entity }) => {
  await StorageAPI.savePlayer(entity);
});

function find(name: string) {
  return world.querySelectorAll('player').find((x) => x.player.name === name);
}

const dhmNpc = world.querySelector('#兑换码') as GameEntity;
dhmNpc.enableInteract = true;
dhmNpc.interactRadius = 5;
dhmNpc.onInteract(async ({ entity }) => {
  await DHM.exchangeCode(entity);
});
